package com.ptkc.ext;

import com.alibaba.fastjson.JSON;
import com.ptkc.core.canal.handler.EventTypeHandler;
import com.ptkc.core.esearch.model.Order;
import com.ptkc.core.esearch.repos.OrderRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author: Mr.Jiao
 * @date: 2018年11月05日
 */
@Slf4j
@Component
public class OrderCanalSyncHandler extends EventTypeHandler<Order> {

    @Autowired
    private OrderRepository repository;


    public OrderCanalSyncHandler() {
        super("runfast", "runfast_goods_sell_record");
    }


    @Override
    public boolean getSubscribe(String database, String table) {
        return this.getDatabase().equalsIgnoreCase(database) && this.getTable().equalsIgnoreCase(table);
    }


    @Override
    public Class<Order> getEntryClass() {
        return Order.class;
    }

    @Override
    public void onInsert(Order order) {
        log.info(JSON.toJSONString(order));
        try {
            boolean isSuccess = repository.save(order);
            if(!isSuccess){
                log.error("记录订单信息失败:{}", JSON.toJSONString(order));
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }

    @Override
    public void onUpdate(Order order) {
        log.info(JSON.toJSONString(order));
        try {
            boolean isSuccess = repository.save(order);
            if(!isSuccess){
                log.error("记录订单信息失败:{}", JSON.toJSONString(order));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }


    @Override
    public void onDelete(Order order) {
        try {
            repository.delete(order);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }



}
